#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Orginal Data Sample
# Generated: Mon Apr 11 22:35:13 2022
##################################################

from distutils.version import StrictVersion

if __name__ == '__main__':
    import ctypes
    import sys
    if sys.platform.startswith('linux'):
        try:
            x11 = ctypes.cdll.LoadLibrary('libX11.so')
            x11.XInitThreads()
        except:
            print "Warning: failed to XInitThreads()"

from PyQt5 import Qt, QtCore
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import uhd
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
import sys
import time
from gnuradio import qtgui


class orginal_data_sample(gr.top_block, Qt.QWidget):

    def __init__(self, antenna="RX2", bw=5e6, device="uhd,type=b200,subdev=A:A,num_recv_frames=128", freq=408e6, obstime=300, pname="B0329+54", prefix=".", refclock="external", rfgain=0, srate=5e6, subdev="A:A"):
        gr.top_block.__init__(self, "Orginal Data Sample")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Orginal Data Sample")
        qtgui.util.check_set_qss()
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "orginal_data_sample")

        if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
            self.restoreGeometry(self.settings.value("geometry").toByteArray())
        else:
            self.restoreGeometry(self.settings.value("geometry", type=QtCore.QByteArray))

        ##################################################
        # Parameters
        ##################################################
        self.antenna = antenna
        self.bw = bw
        self.device = device
        self.freq = freq
        self.obstime = obstime
        self.pname = pname
        self.prefix = prefix
        self.refclock = refclock
        self.rfgain = rfgain
        self.srate = srate
        self.subdev = subdev

        ##################################################
        # Variables
        ##################################################
        self.sky = sky = freq+1.3e9
        self.skyf = skyf = freq if sky <= 0.0 else sky
        self.samp_rate = samp_rate = int(srate)
        self.mjd = mjd = (time.time() / 86400.0)+40587.0
        self.fbsize = fbsize = 10
        self.bfilename = bfilename = prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (pname, skyf/1.0e6, samp_rate/1.0e6, bw/1.0e6,obstime/60,mjd)

        ##################################################
        # Blocks
        ##################################################
        self.uhd_radio = uhd.usrp_source(
        	",".join((device, "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(1),
        	),
        )
        self.uhd_radio.set_clock_source(refclock, 0)
        self.uhd_radio.set_subdev_spec(subdev, 0)
        self.uhd_radio.set_samp_rate(samp_rate)
        self.uhd_radio.set_time_unknown_pps(uhd.time_spec())
        self.uhd_radio.set_center_freq(freq, 0)
        self.uhd_radio.set_gain(rfgain, 0)
        self.uhd_radio.set_antenna(antenna, 0)
        self.uhd_radio.set_bandwidth(samp_rate, 0)
        self.uhd_radio.set_auto_dc_offset(True, 0)
        self.uhd_radio.set_auto_iq_balance(True, 0)
        self.copyblock = blocks.head(gr.sizeof_gr_complex*1, samp_rate*obstime)
        self.blocks_file_sink_0 = blocks.file_sink(gr.sizeof_gr_complex*1, bfilename, True)
        self.blocks_file_sink_0.set_unbuffered(True)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.copyblock, 0), (self.blocks_file_sink_0, 0))
        self.connect((self.uhd_radio, 0), (self.copyblock, 0))

    def closeEvent(self, event):
        self.settings = Qt.QSettings("GNU Radio", "orginal_data_sample")
        self.settings.setValue("geometry", self.saveGeometry())
        event.accept()

    def get_antenna(self):
        return self.antenna

    def set_antenna(self, antenna):
        self.antenna = antenna
        self.uhd_radio.set_antenna(self.antenna, 0)

    def get_bw(self):
        return self.bw

    def set_bw(self, bw):
        self.bw = bw
        self.set_bfilename(self.prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (self.pname, self.skyf/1.0e6, self.samp_rate/1.0e6, self.bw/1.0e6,self.obstime/60,self.mjd))

    def get_device(self):
        return self.device

    def set_device(self, device):
        self.device = device

    def get_freq(self):
        return self.freq

    def set_freq(self, freq):
        self.freq = freq
        self.uhd_radio.set_center_freq(self.freq, 0)
        self.set_skyf(self.freq if self.sky <= 0.0 else self.sky)
        self.set_sky(self.freq+1.3e9)

    def get_obstime(self):
        return self.obstime

    def set_obstime(self, obstime):
        self.obstime = obstime
        self.set_bfilename(self.prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (self.pname, self.skyf/1.0e6, self.samp_rate/1.0e6, self.bw/1.0e6,self.obstime/60,self.mjd))
        self.copyblock.set_length(self.samp_rate*self.obstime)

    def get_pname(self):
        return self.pname

    def set_pname(self, pname):
        self.pname = pname
        self.set_bfilename(self.prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (self.pname, self.skyf/1.0e6, self.samp_rate/1.0e6, self.bw/1.0e6,self.obstime/60,self.mjd))

    def get_prefix(self):
        return self.prefix

    def set_prefix(self, prefix):
        self.prefix = prefix
        self.set_bfilename(self.prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (self.pname, self.skyf/1.0e6, self.samp_rate/1.0e6, self.bw/1.0e6,self.obstime/60,self.mjd))

    def get_refclock(self):
        return self.refclock

    def set_refclock(self, refclock):
        self.refclock = refclock

    def get_rfgain(self):
        return self.rfgain

    def set_rfgain(self, rfgain):
        self.rfgain = rfgain
        self.uhd_radio.set_gain(self.rfgain, 0)


    def get_srate(self):
        return self.srate

    def set_srate(self, srate):
        self.srate = srate
        self.set_samp_rate(int(self.srate))

    def get_subdev(self):
        return self.subdev

    def set_subdev(self, subdev):
        self.subdev = subdev

    def get_sky(self):
        return self.sky

    def set_sky(self, sky):
        self.sky = sky
        self.set_skyf(self.freq if self.sky <= 0.0 else self.sky)

    def get_skyf(self):
        return self.skyf

    def set_skyf(self, skyf):
        self.skyf = skyf
        self.set_bfilename(self.prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (self.pname, self.skyf/1.0e6, self.samp_rate/1.0e6, self.bw/1.0e6,self.obstime/60,self.mjd))

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.set_bfilename(self.prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (self.pname, self.skyf/1.0e6, self.samp_rate/1.0e6, self.bw/1.0e6,self.obstime/60,self.mjd))
        self.uhd_radio.set_samp_rate(self.samp_rate)
        self.uhd_radio.set_bandwidth(self.samp_rate, 0)
        self.copyblock.set_length(self.samp_rate*self.obstime)

    def get_mjd(self):
        return self.mjd

    def set_mjd(self, mjd):
        self.mjd = mjd
        self.set_bfilename(self.prefix+"/B1/psr-%s-%-.1f-%-.1f-%-.1f-%-.1fmin-%9.3f.bin" % (self.pname, self.skyf/1.0e6, self.samp_rate/1.0e6, self.bw/1.0e6,self.obstime/60,self.mjd))

    def get_fbsize(self):
        return self.fbsize

    def set_fbsize(self, fbsize):
        self.fbsize = fbsize

    def get_bfilename(self):
        return self.bfilename

    def set_bfilename(self, bfilename):
        self.bfilename = bfilename
        self.blocks_file_sink_0.open(self.bfilename)


def argument_parser():
    parser = OptionParser(usage="%prog: [options]", option_class=eng_option)
    parser.add_option(
        "", "--antenna", dest="antenna", type="string", default="RX2",
        help="Set Antenna selector [default=%default]")
    parser.add_option(
        "", "--bw", dest="bw", type="eng_float", default=eng_notation.num_to_str(5e6),
        help="Set Band Width [default=%default]")
    parser.add_option(
        "", "--device", dest="device", type="string", default="uhd,type=b200,subdev=A:A,num_recv_frames=128",
        help="Set Device String [default=%default]")
    parser.add_option(
        "", "--freq", dest="freq", type="eng_float", default=eng_notation.num_to_str(408e6),
        help="Set Frequency (in Hz) [default=%default]")
    parser.add_option(
        "", "--obstime", dest="obstime", type="intx", default=300,
        help="Set Runtime in seconds [default=%default]")
    parser.add_option(
        "", "--pname", dest="pname", type="string", default="B0329+54",
        help="Set Pulsar Name [default=%default]")
    parser.add_option(
        "", "--prefix", dest="prefix", type="string", default=".",
        help="Set filename prefix [default=%default]")
    parser.add_option(
        "", "--refclock", dest="refclock", type="string", default="external",
        help="Set Reference clock source [default=%default]")
    parser.add_option(
        "", "--rfgain", dest="rfgain", type="eng_float", default=eng_notation.num_to_str(0),
        help="Set RF Gain [default=%default]")
    parser.add_option(
        "", "--srate", dest="srate", type="eng_float", default=eng_notation.num_to_str(5e6),
        help="Set Sample Rate (in Hz) [default=%default]")
    parser.add_option(
        "", "--subdev", dest="subdev", type="string", default="A:A",
        help="Set Subdev (UHD only) [default=%default]")
    return parser


def main(top_block_cls=orginal_data_sample, options=None):
    if options is None:
        options, _ = argument_parser().parse_args()

    if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
        Qt.QApplication.setGraphicsSystem(style)
    qapp = Qt.QApplication(sys.argv)

    tb = top_block_cls(antenna=options.antenna, bw=options.bw, device=options.device, freq=options.freq, obstime=options.obstime, pname=options.pname, prefix=options.prefix, refclock=options.refclock, rfgain=options.rfgain, srate=options.srate, subdev=options.subdev)
    tb.start()
    tb.show()

    def quitting():
        tb.stop()
        tb.wait()
    qapp.aboutToQuit.connect(quitting)
    qapp.exec_()


if __name__ == '__main__':
    main()
